(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react-dom'), require('react')) :
    typeof define === 'function' && define.amd ? define(['exports', 'react-dom', 'react'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.MathHomework = {}, global.ReactDOM, global.React));
}(this, (function (exports, ReactDOM, React$1) { 'use strict';

    function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

    var ReactDOM__default = /*#__PURE__*/_interopDefaultLegacy(ReactDOM);
    var React__default = /*#__PURE__*/_interopDefaultLegacy(React$1);

    /**
     *
     * @param input 输入的源
     * @param rowColumns 一行多少列
     */
    function extractQuestions(input, rowColumns = 3) {
        let text = input.trim().replace(/(\r\n|\n\r)+/, '\n');
        const rs = [];
        // 逐行解析
        text.split(/\n/).forEach(row => {
            // const items = row.match(/[\S]{2,}/g) || [];
            const items = row.split(/[\s]{2,}/g).filter(Boolean);
            const max = Math.ceil(items.length / rowColumns) * rowColumns;
            for (let i = 0; i < max; i++) {
                rs.push(items[i] || '');
            }
        });
        return rs;
    }
    const Tokens = {
        '×': '*',
        '÷': '/',
        '＋': '+',
        '－': '-',
        '（': '(',
        '）': ')',
    };
    function generateTokensPattern(tokens) {
        const temp = Object.keys(tokens).join('|');
        return new RegExp(`\\s?${temp}\\s?`, 'g');
    }
    // @ts-ignore
    let TokensPattern = generateTokensPattern(Tokens);
    function fixRound(str) {
        if (isNaN(Number(str))) {
            return str;
        }
        const match = str.match(/^([\d]+(?:\.[0]{0,}[^0]+)?)/);
        if (match) {
            return match[1];
        }
        return str;
    }
    function calculateQuestion(input) {
        try {
            const text = input.replace(TokensPattern, (search) => {
                const v = search.trim();
                // @ts-ignore
                return Tokens[v] || v;
            });
            const rs = eval(text);
            const int = parseInt(rs);
            if (int === rs) {
                return int + '';
            }
            return fixRound(rs.toFixed(8));
        }
        catch (err) {
        }
        return '';
    }
    const PurgeTokens = {
        '＋': '+',
        '－': '-',
        '（': '(',
        '）': ')',
    };
    function purgeQuestion(input) {
        return input.replace(/[\s]/g, '').replace(TokensPattern, (search) => {
            const v = search.trim();
            // @ts-ignore
            return PurgeTokens[v] || v;
        });
    }

    const MathQuestion = ({ question, isCalculation, isPurge }) => {
        const [result, setResult] = React$1.useState('');
        const [compactText, setCompactText] = React$1.useState('');
        const [last, setLast] = React$1.useState('');
        const [highlight, setHighlight] = React$1.useState(false);
        // @ts-ignore
        React$1.useEffect(() => {
            if (highlight) {
                let timer = setTimeout(() => {
                    setHighlight(false);
                }, 3000);
                return () => {
                    timer && clearTimeout(timer);
                };
            }
        }, [highlight]);
        React$1.useEffect(() => {
            if (last === '' || last !== result) {
                setLast(result);
                if (last !== '') {
                    setHighlight(true);
                }
            }
        }, [result]);
        React$1.useEffect(() => {
            setCompactText(purgeQuestion(question));
        }, [question]);
        React$1.useEffect(() => {
            if (isCalculation) {
                setResult(calculateQuestion(question));
            }
        }, [question, isCalculation]);
        return (React__default['default'].createElement("div", { className: 'math-question' + (highlight ? ' highlight' : '') },
            React__default['default'].createElement("div", { className: 'question' }, isPurge ? compactText : question),
            isCalculation && result ? (React__default['default'].createElement("div", { className: 'result' }, result)) : null));
    };
    const rangeSize = (start, size) => {
        const range = [];
        for (let i = 0; i < size; i++) {
            range.push(start + i);
        }
        return range;
    };
    const MathQuestions = ({ questions, columns = 3, isPurge: inputPurge, }) => {
        const [isCalculation, setCalculation] = React$1.useState(false);
        const [isPurge, setPurge] = React$1.useState(false);
        React$1.useEffect(() => {
            setPurge(!!inputPurge);
        }, [inputPurge]);
        const style = {
            width: 100 / columns + '%',
        };
        const rows = Math.ceil(questions.length / columns);
        return (React__default['default'].createElement("div", null,
            React__default['default'].createElement("table", { width: '100%' }, rangeSize(0, rows).map(r => (React__default['default'].createElement("tr", null, rangeSize(0, columns).map(i => {
                const q = questions[r * columns + i] || '';
                return React__default['default'].createElement("td", { style: style },
                    React__default['default'].createElement(MathQuestion, { isPurge: isPurge, isCalculation: isCalculation, question: q }));
            }))))),
            React__default['default'].createElement("div", { className: 'actions' },
                React__default['default'].createElement("button", { type: 'button', onClick: () => setCalculation(!isCalculation) },
                    isCalculation ? '隐藏' : '显示',
                    "\u8BA1\u7B97\u7ED3\u679C"),
                React__default['default'].createElement("button", { type: 'button', onClick: () => setPurge(!isPurge) },
                    isPurge ? '隐藏' : '显示',
                    "\u7D27\u51D1\u6A21\u5F0F")),
            React__default['default'].createElement("p", null,
                "\u7D27\u51D1\u6A21\u5F0F\uFF1A\u66FF\u6362\u4E2D\u6587\u5B57\u7B26\u7684 ",
                React__default['default'].createElement("code", null, "\uFF0B"),
                " ",
                React__default['default'].createElement("code", null, "\uFF0D"),
                " ",
                React__default['default'].createElement("code", null, "\uFF08"),
                " ",
                React__default['default'].createElement("code", null, "\uFF09"),
                " \u4E3A\u82F1\u6587\u5B57\u7B26\u4E32")));
    };

    const App = ({ value }) => {
        const [source, setSource] = React$1.useState(value || '');
        const [questions, setQuestions] = React$1.useState([]);
        const [inputColumns, setInputColumns] = React$1.useState(3);
        const [renderColumns, setRenderColumns] = React$1.useState(3);
        React$1.useEffect(() => {
            setQuestions(extractQuestions(source, inputColumns));
        }, [source, inputColumns]);
        return (React__default['default'].createElement("div", null,
            React__default['default'].createElement("div", { className: 'question-input' },
                React__default['default'].createElement("label", null,
                    React__default['default'].createElement("div", null,
                        "\u8F93\u5165\u539F\u59CB\u5185\u5BB9\uFF08\u4E00\u884C ",
                        React__default['default'].createElement("select", { value: inputColumns, onChange: e => setInputColumns(parseInt(e.target.value)) },
                            React__default['default'].createElement("option", null, "2"),
                            React__default['default'].createElement("option", null, "3"),
                            React__default['default'].createElement("option", null, "4"),
                            React__default['default'].createElement("option", null, "5"),
                            React__default['default'].createElement("option", null, "6")),
                        " \u5217\uFF09\uFF1A"),
                    React__default['default'].createElement("textarea", { rows: 5, className: 'source-input', value: source, onChange: e => setSource(e.target.value) }))),
            React__default['default'].createElement("div", null,
                "\u91CD\u65B0\u6392\u7248\u7ED3\u679C\uFF08\u4E00\u884C ",
                React__default['default'].createElement("select", { value: renderColumns, onChange: e => setRenderColumns(parseInt(e.target.value)) },
                    React__default['default'].createElement("option", null, "2"),
                    React__default['default'].createElement("option", null, "3"),
                    React__default['default'].createElement("option", null, "4"),
                    React__default['default'].createElement("option", null, "5"),
                    React__default['default'].createElement("option", null, "6")),
                " \u5217\uFF09\uFF1A"),
            React__default['default'].createElement(MathQuestions, { questions: questions, columns: renderColumns, isPurge: true })));
    };

    function startUp(el, props) {
        return el && ReactDOM__default['default'].render(React.createElement(App, Object.assign({}, (props || {}))), el);
    }

    exports.startUp = startUp;

    Object.defineProperty(exports, '__esModule', { value: true });

})));
